const md5 = require('./md5.js');
import { baseUrl } from "../setting";

function isNumber(obj) {
  return typeof obj === 'number' && !isNaN(obj)
}

export function uploadImg(callback) {
  my.chooseImage({
    sourceType: ['camera', 'album'],
    count: 1,
    success: (res) => {
      if (res.success) {
        const imgUrl = res.apFilePaths[0];
        const secretKey = 'sdksdksdcfsd'
        const data = {
          timeStamp: new Date().getTime() + ''
        }
        let crypt = md5.hexMD5(JSON.stringify(data) + secretKey);
        my.uploadFile({
          url: baseUrl + '/Alipay/upload',
          fileType: 'image',
          fileName: 'file',
          filePath: imgUrl,
          header: {
            'Content-Type': 'multipart/form-data',
            'crypt': crypt
          },
          formData: data,
          success: res => {
            const result = JSON.parse(res.data);
            if (result.status == 200) {
              return callback(result.data.image);
            } else {
              my.showToast({
                type: 'fail',
                content: result.msg,
                duration: 1000,
              });
              return callback(false);
            }
          },
          fail: function (res) {
            my.showToast({
              type: 'fail',
              content: '上传图片失败',
              duration: 1000,
            });
            return callback(false);
          },
        });
      }
    }
  })
}

export function request(config) {
  // 加载loading
  my.showLoading({
    content: '加载中...'
  });
  const secretKey = 'sdksdksdcfsd'
  const timeStamp = new Date().getTime() + '';
  // 解构赋值
  let {
    url = '',
    data = { timeStamp },
    method = 'POST'
  } = { ...config };
  for (let key in data) {
    if (isNumber(data[key])) {
      data[key] += '';
    }
  }
  let crypt = md5.hexMD5(JSON.stringify(data) + secretKey);
  const token = my.getStorageSync({ key: 'token' }).data;
  let header = token ? { token, crypt } : { crypt };

  return new Promise((resolve, reject) => {
    my.request({
      url: baseUrl + url,
      method: method,
      data: { ...data },
      headers: { ...header },
      success: (res) => {
        const app = getApp();

      if(my.getStorageSync({ key: 'successAuth' }).data){
        my.setStorage({ key: 'successAuth', data:0 });
      }
      
        if (res.data && res.data.status === 200) {
          resolve(res.data.data)
        } else if (res.data && res.data.status === 300) { //未授权
          if (token) {
            app.getAuthBase()
          } else {
            app.getAuthUser()
          }
        } else {
          my.showToast({
            type: 'fail',
            content: res.data.msg,
            duration: 2000
          });
          reject(res)
        }
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        setTimeout(() => {
          my.hideLoading();
        }, 400)
      }
    });
  })
}